import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:camera_product_plugin/camera_product_plugin.dart';
import 'package:camera_product_plugin_example/dialog/bluetooth_dialog.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:permission_handler/permission_handler.dart';

import 'dialog/wifi_dialog.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _platformVersion = 'wait';

  dynamic _bluetooth = "wait";
  dynamic _connectWifi = "wait";

  final _cameraProductPlugin = CameraProductPlugin();

  final List<Map<String, dynamic>> _devices = []; // 存储唯一设备
  final Set<String> _deviceMacSet = {}; // 记录已添加的 deviceMac
  final List<Map<String, dynamic>> _wifis = []; // 存储唯一wifi
  final Set<String> _wifiSet = {}; // 记录已添加的WIFI
  int selectWifiIndex = -1; //选择的WIFI序号
  bool passwordVisible = true;
  final myController = TextEditingController();

  List<String> countries = <String>[
    'Belgium',
    'France',
    'Italy',
    'Germany',
    'Spain',
    'Portugal'
  ];

  @override
  void initState() {
    super.initState();
    _cameraProductPlugin.onListening((event) {
      print('------- platform event -----------');
      print(event);

      Map<String, dynamic> mapData = Map<String, dynamic>.from(event);
      //发现新设备
      if (mapData.containsKey("find_new_device")) {
        Map<String, dynamic> bleDevice =
            json.decode(mapData["find_new_device"]);
        print(bleDevice["mBleName"]);
        if (!_deviceMacSet.contains(bleDevice["mBleAddress"])) {
          setState(() {
            _devices.add(bleDevice);
            _deviceMacSet.add(bleDevice["mBleAddress"]);
          });
        }
        showBluetoothListDialog(_devices).then((onValue) {
          print("选择了  ==   ${onValue?["mBleName"]}");

          //连接设备
          callConnectBluetooth(onValue);
        });
      }
      //WIFI信息
      if (mapData.containsKey("find_wifi")) {
        print("发现WIFI");
        Map<String, dynamic> wifiInfo = json.decode(mapData["find_wifi"]);
        if (!_wifiSet.contains(wifiInfo["ssid"])) {
          print("添加WIFI");
          setState(() {
            _wifis.add(wifiInfo);
            _wifiSet.add(wifiInfo["ssid"]);
          });
        }
      }
      //拍照
      if (mapData.containsKey("take_photo_code")) {
        print("拍照");
        String code = mapData["take_photo_code"];
        print("拍照状态 ===   $code");
      }
    });
  }

  @override
  void dispose() {
    myController.dispose();
    super.dispose();
  }

  Future<void> callReset() async {
    setState(() {
      _platformVersion = 'wait';
      _bluetooth = "wait";
      _connectWifi = "wait";

      _devices.clear();
      _deviceMacSet.clear();

      _wifis.clear();
      _wifiSet.clear();
      selectWifiIndex = -1;
    });
  }

  Future<void> callInitCameraSDK() async {
    try {
      String initSdk =
          await _cameraProductPlugin.initCameraSDK() ?? 'Unknown error';
      print("====初始化相机SDK=====  $initSdk");
    } on PlatformException {
      print("====初始化相机SDK异常");
    }
  }

  Future<void> callNativeV() async {
    try {
      String platformVersion =
          await _cameraProductPlugin.getPlatformVersion() ??
              'Unknown platform version';
      setState(() {
        _platformVersion = platformVersion;
      });
    } on PlatformException {
      setState(() {
        _platformVersion = 'Failed to call platform method';
      });
    }
  }

  Future<void> callScanBluetooth() async {
    try {
      bool permission = await requestNearDevicePermission(context);
      if (permission) {
        String? device = await _cameraProductPlugin.scanBluetooth();

        setState(() {
          _bluetooth = device;
        });
      }
    } on PlatformException {
      setState(() {
        _bluetooth = "没检测到";
      });
    }
  }

  Future<void> callConnectBluetooth(Map<String, dynamic>? device) async {
    try {
      print("====开始连接蓝牙=====");
      String? state =
          await _cameraProductPlugin.connectBluetooth(json.encode(device));
    } on PlatformException {
      print("连接蓝牙异常");
    }
  }

  Future<void> callScanWIFI() async {
    try {
      // bool permission = await requestWIFIPermission(context);
      // if (permission) {
      print("====开始扫描WIFI=====");
      String? connectWifi = await _cameraProductPlugin.scanWIFI();
      setState(() {
        _connectWifi = connectWifi;
      });
      // }
    } on PlatformException {
      setState(() {
        _connectWifi = "没检测到";
      });
    }
  }

  //连接wifi
  Future<void> callConnectWIFI(Map<String, dynamic> wifiMap) async {
    try {
      print("====开始连接WIFI=====");
      String? state =
          await _cameraProductPlugin.connectWIFI(json.encode(wifiMap));
    } on PlatformException {
      print("连接WIFI");
    }
  }

  ///拍照
  Future<void> callTakePhoto() async {
    try {
      print("====开始拍照=====");
      bool permission = await getStoragePermission();
      if (permission) {
        String? photo = await _cameraProductPlugin.takePhoto();
        print("====拍照结果=====${photo}");
      } else {
        print("====开始拍照=====没有读写权限");
      }
    } on PlatformException {
      print("拍照异常");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: FlutterSmartDialog.init(),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('蓝牙连接摄像头Demo'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              Row(
                children: [
                  ElevatedButton(onPressed: callReset, child: Text("重置")),
                  // ElevatedButton(onPressed: callNativeV, child: Text("版本号")),
                  ElevatedButton(
                      onPressed: callInitCameraSDK, child: Text("初始化")),
                  ElevatedButton(
                      onPressed: callScanBluetooth, child: Text("扫描蓝牙")),
                  ElevatedButton(
                      onPressed: callScanWIFI, child: Text("扫描WIFI")),
                ],
              ),
              Text('Running on: $_platformVersion\n'),
              Text('蓝牙: $_bluetooth\n'),
              Text('WIFI: $_connectWifi\n'),
              MyWifiDialog(_wifis, (index) {
                print("选择了 WIFI ${_wifis[index]['ssid']}");
                setState(() {
                  selectWifiIndex = index;
                });
              }),
              Visibility(
                  visible: selectWifiIndex >= 0,
                  child: Column(
                    children: [
                      if (selectWifiIndex >= 0) ...[
                        Text(
                          "选择的WIFI是： ${_wifis[selectWifiIndex]['ssid']}",
                          style:
                              TextStyle(color: Colors.redAccent, fontSize: 18),
                        ),
                      ],
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text("请输入密码："),
                          Expanded(
                              child: TextField(
                            controller: myController,
                            obscureText: passwordVisible,
                            decoration: InputDecoration(
                                labelText: 'password',
                                suffixIcon: IconButton(
                                    onPressed: () {
                                      setState(() {
                                        passwordVisible = !passwordVisible;
                                      });
                                    },
                                    icon: Icon(passwordVisible
                                        ? Icons.visibility_off
                                        : Icons.visibility))),
                          ))
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          ElevatedButton(
                              onPressed: () {
                                print('连接WIFI');
                                if (selectWifiIndex == -1) {
                                  SmartDialog.showToast("请先选择WIFI");
                                  return;
                                }
                                // if (myController.text.isEmpty) {
                                //   SmartDialog.showToast(
                                //       "请输入 ${_wifis[selectWifiIndex]['ssid']} 的密码");
                                //   return;
                                // }

                                _wifis[selectWifiIndex]['password'] =
                                    "lanjing2022";
                                // myController.text;

                                callConnectWIFI(_wifis[selectWifiIndex]);
                              },
                              child: Text("连接WIFI")),
                          ElevatedButton(
                              onPressed: () {
                                callTakePhoto();
                              },
                              child: Text("拍照")),
                        ],
                      )
                    ],
                  )),
            ],
          ),
        ),
      ),
    );
  }
}

// 申请蓝牙权限
Future<bool> requestNearDevicePermission(BuildContext context,
    {Function? confirm, Function? cancel}) async {
  if (Platform.isAndroid) {
    // PermissionStatus status = await Permission.bluetooth.status;

    PermissionStatus status = await Permission.bluetoothScan.request();
    PermissionStatus status1 = await Permission.bluetoothConnect.request();

    PermissionStatus loctionStatus =
        await Permission.locationWhenInUse.request();

    bool isPermission = false;
    //String androidVersion = androidInfo.version.release;
    bool isAndroidVersionGreaterThan12 =
        await getNearVersion(); //androidVersion.compareTo('12') > 0;
    if (isAndroidVersionGreaterThan12) {
      isPermission = status.isGranted && status1.isGranted;
    } else {
      isPermission = loctionStatus.isGranted;
    }
    return isPermission;
  }
  return true;
}

Future<bool> getNearVersion() async {
  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
  bool isAndroidVersionGreaterThan12 = androidInfo.version.sdkInt >= 31;
  return isAndroidVersionGreaterThan12;
}

//请求WIFI权限
// Future<bool> requestWIFIPermission(BuildContext context,
//     {Function? confirm, Function? cancel}) async {
//   if (Platform.isAndroid) {
//     PermissionStatus wifiStatus = await Permission.nearbyWifiDevices.request();
//     return wifiStatus.isGranted;
//   }
//   return true;
// }

//请求存储权限
Future<bool> getStoragePermission() async {
  if (Platform.isAndroid) {
    PermissionStatus storage11 =
        await Permission.manageExternalStorage.request();
    PermissionStatus storage = await Permission.storage.request();

    bool isStoragePermission = false;
    bool isAndroidVersionGreaterThan11 = await getNearVersion();
    if (isAndroidVersionGreaterThan11) {
      isStoragePermission = storage.isGranted && storage11.isGranted;
    }

    PermissionStatus camera = await Permission.camera.request();
    print("存储权限状态 === ${isStoragePermission} ===  ${camera.isGranted}");
    return storage.isGranted && camera.isGranted;
  }
  return true;
}
